<template>
  <!-- 一对一关联选择组件 -->
  <div class="relation-select">
    <el-select
      :modelValue="selectedItems.length > 0 ? pps.modelValue : undefined"
      style="width: 100%"
      :disabled="disabled"
      :size="size"
      :clearable="clearable"
      :placeholder="placeholder"
      :popper-append-to-body="false"
      popper-class="relation-select-popper"
      @visible-change="onVisibleChange"
      @remove-tag="onRemoveTag"
      @clear="onClear"
    >
      <el-option
        v-for="item in selectedItems"
        :key="item[pps.props.value]"
        :label="item[pps.props.label]"
        :value="item[pps.props.value]"
      />
    </el-select>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formSelectStudentAI',
};
</script>

<script setup lang="ts">
import { getUUID } from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { StudentController } from '@/api/generated';
import FormSelectStudentAI from '@/pages/aiform/formSelectStudentAI/formSelectStudentAI.vue';
import { ANY_OBJECT } from '@/types/generic';
import { Dialog } from '@/components/Dialog';
import { defineEmits, withDefaults, defineProps } from 'vue';

const emit = defineEmits<{
  'update:modelValue': [string | number | StudentData[]];
  change: [string | number | StudentData[], string | number | StudentData[]];
}>();

const pps = withDefaults(
  defineProps<{
    modelValue: string | number | StudentData[] | undefined;
    props?: ANY_OBJECT;
    disabled?: boolean;
    size?: '' | 'default' | 'large' | 'small';
    clearable?: boolean;
    placeholder?: string;
  }>(),
  {
    size: 'default',
    props: () => {
      return {
        label: 'name',
        value: 'id',
      };
    },
    disabled: false,
    clearable: false,
  },
);

const widgetId = getUUID();
const selectedItems = ref<ANY_OBJECT[]>([]);
const selectedValue = ref<string | number | StudentData[] | undefined>(pps.modelValue);

const handlerEditOperate = (item: StudentData) => {
  selectedItems.value = [];
  if (item) selectedItems.value.push(item);
  if (!checkSelectChange()) return;
  emitChange();
};

const onVisibleChange = (visible: boolean) => {
  if (visible) {
    Dialog.show<ANY_OBJECT>(
      '选择学生',
      FormSelectStudentAI,
      {
        area: ['1200px', '650px'],
        offset: '100px',
      },
      {
        modelValue: selectedItems.value,
        props: pps.props,
        path: 'formSelectStudentAI/' + widgetId,
      },
      {
        width: '1200px',
        height: '650px',
        pathName: '/thirdParty/formSelectStudentAI',
      },
    ).then(res => {
      handlerEditOperate(res);
    });
  }
};

const onRemoveTag = (val: ANY_OBJECT) => {
  selectedItems.value = selectedItems.value.filter(item => {
    return item[pps.props.value] !== val;
  });
  emitChange();
};
const onClear = () => {
  selectedItems.value = [];
  emitChange();
};

const emitChange = () => {
  let tempValue;
  tempValue = selectedItems.value[0] || {};
  emit('update:modelValue', tempValue[pps.props.value]);
  emit('change', tempValue[pps.props.value], selectedItems.value[0]);
};
const checkSelectChange = () => {
  let valueIdString = pps.modelValue || '';
  let selectedItemsString = selectedItems.value
    .sort((item1, item2) => {
      if (item1[pps.props.value] === item2[pps.props.value]) return 0;
      return item1[pps.props.value] < item2[pps.props.value] ? -1 : 1;
    })
    .map(item => item[pps.props.value])
    .join(',');
  return valueIdString !== selectedItemsString;
};
const getSelectItemList = () => {
  if (pps.modelValue == null || pps.modelValue === '') {
    selectedItems.value = [];
  } else {
    let params: ANY_OBJECT = {
      studentId: pps.modelValue,
    };
    StudentController.view(params)
      .then(res => {
        if (res.data) {
          selectedItems.value = [res.data];
        }
      })
      .catch(e => {
        console.log(e);
      });
  }
};

watch(
  () => pps.modelValue,
  newVal => {
    selectedValue.value = newVal;
    getSelectItemList();
  },
  {
    immediate: true,
  },
);
</script>

<style scoped>
.relation-select ::v-deep .relation-select-popper {
  display: none;
}

.relation-select ::v-deep .el-dialog__header {
  height: 42px;
  line-height: 42px;
  padding: 0px 20px;
  background-color: #f8f8f8;
}
.relation-select ::v-deep .el-dialog__title {
  color: #333;
  font-size: 14px;
}
.relation-select ::v-deep .el-dialog__headerbtn {
  top: 12px;
}
.relation-select ::v-deep .el-dialog__body {
  padding: 25px;
}
</style>
